package net.expectx.micro.shop.api.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.google.common.base.Strings;
import io.swagger.annotations.*;

import net.expectx.common.single.base.BaseConstants;
import net.expectx.common.single.base.BaseResult;
import net.expectx.micro.shop.api.common.ApiConstants;
import net.expectx.micro.shop.api.common.ApiResult;
import net.expectx.micro.shop.api.common.ApiResultConstants;
import net.expectx.micro.shop.api.common.util.ApiUtils;
import net.expectx.micro.shop.api.validator.NotNullValidator;
import net.expectx.micro.shop.dao.bean.MemberUserReceivingAddress;
import net.expectx.micro.shop.dao.bean.MemberUserReceivingAddressExample;
import net.expectx.micro.shop.rpc.api.MemberUserReceivingAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author lijian
 */
@Api(tags = "收货地址",description = "收货地址相关接口")
@Controller
@RequestMapping("/member/receivingAddress")
public class MemberUserReceivingAddressController {
    @Autowired
    private MemberUserReceivingAddressService memberUserReceivingAddressService;


    @ApiOperation(value = "加载会员收货地址(需)")
    @ApiImplicitParams({
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @net.expectx.micro.shop.api.authorization.annotation.Authorization
    public ResponseEntity<ApiResult> list(HttpServletRequest request) throws Exception{
        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }
        MemberUserReceivingAddressExample memberUserReceivingAddressExample=new MemberUserReceivingAddressExample();
        memberUserReceivingAddressExample.createCriteria().andIsDeletedEqualTo(ApiConstants.NO).andUserIdEqualTo(userId);
        memberUserReceivingAddressExample.setOrderByClause("gmt_modified desc");
        List<MemberUserReceivingAddress>memberUserReceivingAddresses=memberUserReceivingAddressService.selectByExample(memberUserReceivingAddressExample);
        return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, memberUserReceivingAddresses), HttpStatus.OK);
    }

    @ApiOperation(value = "根据ID获取收货地址(需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "Integer", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
    })
    @RequestMapping(value = "get", method = RequestMethod.GET)
    @net.expectx.micro.shop.api.authorization.annotation.Authorization
    public ResponseEntity<ApiResult> get(
            @RequestParam(required = true, value = "id") Long id) throws Exception{
        FluentValidator fluentValidator = FluentValidator.checkAll();
        if (!Strings.isNullOrEmpty(String.valueOf(id))) {
            fluentValidator.on(String.valueOf(id), new NotNullValidator("主键ID"));
        }
        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }
        MemberUserReceivingAddress memberUserReceivingAddress=memberUserReceivingAddressService.selectByPrimaryKey(id);
        return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, memberUserReceivingAddress), HttpStatus.OK);
    }

    @ApiOperation(value = "保存收货地址(需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realName", value = "真实姓名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "area", value = "所在地区", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "areaIds", value = "所在地区主键集合", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址详情", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认地址(0:不是 1：是)", required = true, dataType = "Integer", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
            @ApiResponse(code = 50021, message = "数据保存异常")
    })
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @net.expectx.micro.shop.api.authorization.annotation.Authorization
    public ResponseEntity<ApiResult> save(
            @RequestParam(required = true, value = "realName") String realName,
            @RequestParam(required = true, value = "phone") String phone,
            @RequestParam(required = true, value = "area") String area,
            @RequestParam(required = true, value = "areaIds") String areaIds,
            @RequestParam(required = true, value = "address") String address,
            @RequestParam(required = true, value = "isDefault",defaultValue = "0") Byte isDefault,
            HttpServletRequest request) throws Exception {
        FluentValidator fluentValidator = FluentValidator.checkAll();

        if (Strings.isNullOrEmpty(realName)) {
            fluentValidator.on(realName, new NotNullValidator("真实姓名"));
        }
        if (Strings.isNullOrEmpty(phone)) {
            fluentValidator.on(phone, new NotNullValidator("手机号"));
        }
        if (Strings.isNullOrEmpty(area)) {
            fluentValidator.on(area, new NotNullValidator("所在地区"));
        }
        if (Strings.isNullOrEmpty(areaIds)) {
            fluentValidator.on(areaIds, new NotNullValidator("所在地区主键集合"));
        }
        if (Strings.isNullOrEmpty(address)) {
            fluentValidator.on(address, new NotNullValidator("地址详情"));
        }

        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }
        if (!areaIds.contains(",")){
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.FAILED,"地区集合请以','分割"), HttpStatus.OK);
        }
        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }
        if(1==isDefault){
            MemberUserReceivingAddressExample memberUserReceivingAddressExample=new MemberUserReceivingAddressExample();
            memberUserReceivingAddressExample.createCriteria().andUserIdEqualTo(userId);
            MemberUserReceivingAddress memberUserReceivingAddress=new MemberUserReceivingAddress();
            memberUserReceivingAddress.setIsDefault(ApiConstants.NO);
            memberUserReceivingAddressService.updateByExampleSelective(memberUserReceivingAddress,memberUserReceivingAddressExample);
        }
        MemberUserReceivingAddress memberUserReceivingAddress = new MemberUserReceivingAddress();
        memberUserReceivingAddress.setGmtCreate(System.currentTimeMillis());
        memberUserReceivingAddress.setGmtModified(System.currentTimeMillis());
        memberUserReceivingAddress.setIsDeleted(BaseConstants.NO);
        memberUserReceivingAddress.setUserId(userId);
        memberUserReceivingAddress.setAddress(address);
        memberUserReceivingAddress.setArea(area);
        memberUserReceivingAddress.setPhone(phone);
        memberUserReceivingAddress.setRealName(realName);
        memberUserReceivingAddress.setAreaIds(areaIds);
        memberUserReceivingAddress.setIsDefault(isDefault);
        BaseResult baseResult=memberUserReceivingAddressService.insertSelective(memberUserReceivingAddress);
        return new ResponseEntity<>(new ApiResult(baseResult), HttpStatus.OK);
    }

    @ApiOperation(value = "更新收货地址(需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "realName", value = "真实姓名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "area", value = "所在地区", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "areaIds", value = "所在地区主键集合", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址详情", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认地址", required = true, dataType = "Integer", paramType = "query"),

    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
            @ApiResponse(code = 50022, message = "数据更新异常"),
            @ApiResponse(code = 50020, message = "暂无数据"),

    })
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @net.expectx.micro.shop.api.authorization.annotation.Authorization
    public ResponseEntity<ApiResult> update(
            @RequestParam(required = true, value = "id") Long id,
            @RequestParam(required = true, value = "realName") String realName,
            @RequestParam(required = true, value = "phone") String phone,
            @RequestParam(required = true, value = "area") String area,
            @RequestParam(required = true, value = "areaIds") String areaIds,
            @RequestParam(required = true, value = "address") String address,
            @RequestParam(required = true, value = "isDefault",defaultValue = "0") Byte isDefault,
            HttpServletRequest request) {
        FluentValidator fluentValidator = FluentValidator.checkAll();
        if (Strings.isNullOrEmpty(String.valueOf(id))) {
            fluentValidator.on(String.valueOf(id), new NotNullValidator("主键"));
        }
        if (Strings.isNullOrEmpty(realName)) {
            fluentValidator.on(realName, new NotNullValidator("真实姓名"));
        }
        if (Strings.isNullOrEmpty(phone)) {
            fluentValidator.on(phone, new NotNullValidator("手机号"));
        }
        if (Strings.isNullOrEmpty(area)) {
            fluentValidator.on(area, new NotNullValidator("所在地区"));
        }
        if (Strings.isNullOrEmpty(areaIds)) {
            fluentValidator.on(areaIds, new NotNullValidator("所在地区主键集合"));
        }
        if (Strings.isNullOrEmpty(address)) {
            fluentValidator.on(address, new NotNullValidator("地址详情"));
        }

        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }
        if (!areaIds.contains(",")){
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.FAILED,"地区集合请以','分割"), HttpStatus.OK);
        }
        MemberUserReceivingAddress memberUserReceivingAddress = memberUserReceivingAddressService.selectByPrimaryKey(id);
        if (null == memberUserReceivingAddress){
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.EXCEPTION_DATA_BASE_NO, null), HttpStatus.OK);
        }
        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }
        if (!memberUserReceivingAddress.getUserId().equals(userId)){
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.FAILED,"当前用户无此主键数据"), HttpStatus.OK);
        }
        if(1==isDefault){
            MemberUserReceivingAddressExample memberUserReceivingAddressExample=new MemberUserReceivingAddressExample();
            memberUserReceivingAddressExample.createCriteria().andUserIdEqualTo(userId);
            MemberUserReceivingAddress receivingAddress=new MemberUserReceivingAddress();
            receivingAddress.setIsDefault(ApiConstants.NO);
            memberUserReceivingAddressService.updateByExampleSelective(receivingAddress,memberUserReceivingAddressExample);
        }
        memberUserReceivingAddress.setGmtCreate(System.currentTimeMillis());
        memberUserReceivingAddress.setGmtModified(System.currentTimeMillis());
        memberUserReceivingAddress.setIsDeleted(BaseConstants.NO);
        memberUserReceivingAddress.setAddress(address);
        memberUserReceivingAddress.setArea(area);
        memberUserReceivingAddress.setPhone(phone);
        memberUserReceivingAddress.setRealName(realName);
        memberUserReceivingAddress.setAreaIds(areaIds);
        memberUserReceivingAddress.setIsDefault(isDefault);
        BaseResult baseResult=memberUserReceivingAddressService.updateByPrimaryKeySelective(memberUserReceivingAddress);
        return new ResponseEntity<>(new ApiResult(baseResult), HttpStatus.OK);
    }

    @ApiOperation(value = "主键集合删除收货地址(需)",notes = "id集合请以','分割")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "主键ID集合", required = true, dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
            @ApiResponse(code = 50023, message = "数据删除异常")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    @net.expectx.micro.shop.api.authorization.annotation.Authorization
    public ResponseEntity<ApiResult> remove(
            @RequestParam(required = true, value = "ids") String ids,HttpServletRequest request) {
        FluentValidator fluentValidator = FluentValidator.checkAll();
        if (Strings.isNullOrEmpty(ids)) {
            fluentValidator.on(ids, new NotNullValidator("ID集合"));
        }
        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }
        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }
        MemberUserReceivingAddressExample memberUserReceivingAddressExample=new MemberUserReceivingAddressExample();
        List<Long>longs=new ArrayList<>();
        for (String id:ids.split(",")){
            longs.add(Long.valueOf(id));
        }
        memberUserReceivingAddressExample.createCriteria().andUserIdEqualTo(userId).andIdIn(longs);
        return new ResponseEntity<>(new ApiResult(memberUserReceivingAddressService.deleteByExample(memberUserReceivingAddressExample)), HttpStatus.OK);
    }
    @ApiOperation(value = "设为默认地址(需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "Integer", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 502, message = "令牌失效，请重新登录"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
            @ApiResponse(code = 50022, message = "数据更新异常"),
            @ApiResponse(code = 50020, message = "暂无数据"),
    })
    @RequestMapping(value = "defaultAddress", method = RequestMethod.POST)
    @net.expectx.micro.shop.api.authorization.annotation.Authorization
    public ResponseEntity<ApiResult> defaultAddress(@RequestParam(required = true, value = "id") Long id,HttpServletRequest request) throws Exception{
        FluentValidator fluentValidator = FluentValidator.checkAll();
        if (!Strings.isNullOrEmpty(String.valueOf(id))) {
            fluentValidator.on(String.valueOf(id), new NotNullValidator("主键ID"));
        }
        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }

        MemberUserReceivingAddress memberUserReceivingAddress = memberUserReceivingAddressService.selectByPrimaryKey(id);
        if (null == memberUserReceivingAddress){
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.EXCEPTION_DATA_BASE_NO, null), HttpStatus.OK);
        }
        Long userId = ApiUtils.getUserId(request);
        if (userId == -1) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.ERROR_UNAUTHORIZED, null), HttpStatus.OK);
        }
        if (!memberUserReceivingAddress.getUserId().equals(userId)){
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.FAILED,"当前用户无此主键数据"), HttpStatus.OK);
        }
        MemberUserReceivingAddressExample memberUserReceivingAddressExample=new MemberUserReceivingAddressExample();
        memberUserReceivingAddressExample.createCriteria().andUserIdEqualTo(userId);
        MemberUserReceivingAddress receivingAddress=new MemberUserReceivingAddress();
        receivingAddress.setIsDefault(ApiConstants.NO);
        memberUserReceivingAddressService.updateByExampleSelective(receivingAddress,memberUserReceivingAddressExample);


        memberUserReceivingAddress.setGmtModified(System.currentTimeMillis());
        memberUserReceivingAddress.setIsDefault(ApiConstants.YES);
        BaseResult baseResult=memberUserReceivingAddressService.updateByPrimaryKeySelective(memberUserReceivingAddress);
        return new ResponseEntity<>(new ApiResult(baseResult), HttpStatus.OK);
    }

}
